'use strict';
const uniID = require('uni-id-common');
exports.main = async (event, context) => {
  // 1. 解析请求体
  let body = event;
  if (event.body !== undefined) {
    try {
      body = JSON.parse(event.body);
    } catch (e) {
      return { code: 400, msg: "请求体解析失败" };
    }
  }
  
  const { uniIdToken,day } = body;
  
  // 2. 验证token获取uid
  const uniIDIns = uniID.createInstance({ context });
	let uid;
    const tokenInfo = await uniIDIns.checkToken(uniIdToken);
    uid = tokenInfo.uid;
    if (!uid) {
      return { code: 403, msg: "身份验证失败" };
    }
	
	// 2.2. 参数存在性检查
	if (!day) {
	    return {
	        code: 400,
	        msg: "缺少必要的参数day"
	    };
	}
	// 2.3. 日期格式校验
	const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
	if (!dateRegex.test(day)) {
	    return {
	        code: 400,
	        msg: "日期格式不正确，应为 YYYY-MM-DD 格式"
	    };
	}
	const dateObj = new Date(day);
	if (isNaN(dateObj.getTime())) {
	    return {
	        code: 400,
	        msg: "提供的日期无效"
	    };
	}
  
  // 3. 查询sc_relations表获取关联的consultant_id
  try {
    const db = uniCloud.database();
    const relationCollection = db.collection('sc_relations');
    
    // 查询当前用户作为督导的所有咨询师关系
    const relationRes = await relationCollection.where({
      supervisor_id: uid
    }).get();
    
    // 如果没有关联的咨询师，直接返回
    if (!relationRes.data || relationRes.data.length === 0) {
      return {
        code: 404,
        msg: "未找到关联的咨询师",
        data: {
          supervisor_id: uid,
          consultants: []
        }
      };
    }
    
    // 4. 获取所有咨询师ID
    const consultantIds = relationRes.data.map(item => item.consultant_id);
    console.log(consultantIds)
    /// 5. 查询这些咨询师的时间表
	const scheduleCollection = db.collection('consultant_schedule');
	const scheduleRes = await scheduleCollection
	  .where({
		user: db.command.in(consultantIds),
		day: day // 添加日期筛选条件到数据库查询
	  })
	  .orderBy('day', 'asc')
	  .get();

	// 6. 处理查询结果 - 提取并合并 freeSlots
	const allFreeSlots = scheduleRes.data.flatMap(schedule => schedule.freeSlots || []);

	// 去重和排序
	const uniqueFreeSlots = [...new Set(allFreeSlots)].sort((a, b) => {
	  const timeToMinutes = (timeStr) => {
		const [hours, minutes] = timeStr.split(':').map(Number);
		return hours * 60 + minutes;
	  };
	  const [startA] = a.split('-');
	  const [startB] = b.split('-');
	  return timeToMinutes(startA) - timeToMinutes(startB);
	});
    
    
    return {
      code: 0,
      msg: "查询成功",
      data: {
        supervisor_id: uid,
        schedules: uniqueFreeSlots
      }
    };
    
  } catch (e) {
    console.error("数据库查询异常:", e);
    return { 
      code: 500, 
      msg: "数据库查询失败",
      error: e.message 
    };
  }
};